package com.bristua.mall.common.biz;

import com.bristua.mall.common.dao.TCodeMapper;
import com.bristua.mall.common.enums.CommonCode;
import com.bristua.mall.common.exception.BizException;
import com.bristua.mall.common.model.TCode;
import com.bristua.mall.common.model.condition.TCodeExample;
import com.bristua.mall.common.utils.DateUtil;
import com.bristua.mall.common.utils.SequenceUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2019/4/28.
 */
@Service
public class ValidateCodeBiz {

    @Resource
    private TCodeMapper tCodeMapper;

    private int minute = 10;

    public String validateCode(String phone,String code){
        TCodeExample tCodeExample = new TCodeExample();
        tCodeExample.setOrderByClause("create_time desc");
        tCodeExample.createCriteria().andCodeEqualTo(code).andPhoneEqualTo(phone);
        List<TCode> tCodes = tCodeMapper.selectByExample(tCodeExample);
        if(tCodes==null || tCodes.size()==0){
            throw new BizException(CommonCode.VALIDATE_CODE_FAIL.getCode(),CommonCode.VALIDATE_CODE_FAIL.getMsg());
        }else{
            TCode tCode = tCodes.get(0);
            if("1".equals(String.valueOf(tCode.getStatus()))){
                throw new BizException(CommonCode.VALIDATE_CODE_FAIL.getCode(),CommonCode.VALIDATE_CODE_FAIL.getMsg());
            }
            if("2".equals(String.valueOf(tCode.getStatus()))){
                throw new BizException(CommonCode.VALIDATE_CODE_EXPIRE.getCode(),CommonCode.VALIDATE_CODE_EXPIRE.getMsg());
            }
            String createTime = tCode.getCreateTime();

            int i = DateUtil.timeDifference(createTime, DateUtil.getDate(), DateUtil.FORMAT1, DateUtil.MINUTE);

            if(i>10){
                tCode.setStatus(2);
                tCodeMapper.updateByPrimaryKeySelective(tCode);
                return "2";//过期
            }
            return "0";
        }
    }

    public String createCode(String phone){
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        TCode tCode = new TCode();
        tCode.setCodeId(SequenceUtil.nextId());
        tCode.setCode(code);
        tCode.setCreateTime(DateUtil.getDateTime3());
        tCode.setStatus(0);
        tCode.setPhone(phone);
        tCodeMapper.insert(tCode);
        return code;
    }


    public void udpateCodeStatus(String phone,String code){
        TCodeExample tCodeExample = new TCodeExample();
        tCodeExample.createCriteria().andCodeEqualTo(code).andPhoneEqualTo(phone);
        List<TCode> tCodes = tCodeMapper.selectByExample(tCodeExample);
        if(tCodes!=null && tCodes.size()>0){
            TCode tCode = tCodes.get(0);
            tCode.setStatus(1);
            tCodeMapper.updateByPrimaryKeySelective(tCode);
        }

    }

}
